﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cs2102BookingSystem.Models;
using System.Web.UI.WebControls;
using System.Data.Objects;
using System.Data.Objects.SqlClient;
using System.Globalization;
using System.IO;

namespace Cs2102BookingSystem.Controllers
{
    public class AdminMainController : Controller
    {
        //
        // GET: /AdminMain/

        private BookingEntities _hotelEntity = new BookingEntities();
        //
        // GET: /MainSearch/

        public ActionResult Index()
        {
            try{
                var returnBestHotel = (from bookingTrans in _hotelEntity.BOOKING
                                       group bookingTrans by new { bookingTrans.H_NAME, bookingTrans.H_COUNTRY, bookingTrans.H_BRANCHNAME } into hotelByName
                                       select new
                                       {
                                           Hotel = hotelByName.Key.H_NAME,
                                           Branch = hotelByName.Key.H_BRANCHNAME,
                                           Country = hotelByName.Key.H_COUNTRY,
                                           Total_Bookings = hotelByName.Count(),
                                           Total_Rooms = hotelByName.Sum(bookingTrans => bookingTrans.NOOFROOM),
                                           Total_SGD = hotelByName.Sum(
                                                                         bookingTrans => bookingTrans.PRICEPERROOM * bookingTrans.NOOFROOM * EntityFunctions.DiffDays(bookingTrans.STARTDATE, bookingTrans.ENDDATE)
                                                                      )
                                       });
                ViewData["BestHotel"] = returnBestHotel.OrderByDescending(hotel => hotel.Total_SGD).ToList().Take(10);
            }catch(Exception e)
            {

            }
            try
            {
                var returnHotelChain = (from bookingTrans in _hotelEntity.BOOKING
                                       group bookingTrans by new { bookingTrans.H_NAME } into hotelByName
                                       select new
                                       {
                                           Hotel_Chain = hotelByName.Key.H_NAME,
                                           Number_Of_Branches = (from hotel in _hotelEntity.HOTEL
                                                                 where hotel.HOTEL_NAME == hotelByName.Key.H_NAME
                                                                 select hotel).Count(),
                                           Total_Bookings = hotelByName.Count(),
                                           Total_Rooms = hotelByName.Sum(bookingTrans => bookingTrans.NOOFROOM),
                                           Total_SGD = hotelByName.Sum(
                                                                         bookingTrans => bookingTrans.PRICEPERROOM * bookingTrans.NOOFROOM * EntityFunctions.DiffDays(bookingTrans.STARTDATE, bookingTrans.ENDDATE)
                                                                      )
                                       });
                ViewData["HotelChain"] = returnHotelChain.OrderByDescending(hotel => hotel.Total_SGD).ToList().Take(10);
            }
            catch (Exception e)
            {

            }

            try
            {
                var returnMonths = (from bookingTrans in _hotelEntity.BOOKING
                                    group bookingTrans by new { bookingTrans.STARTDATE.Month, bookingTrans.STARTDATE.Year} into month
                                       select new
                                       {
                                           Month = month.Key.Month,
                                           Year = month.Key.Year,
                                           Total_Number_Of_Bookings = month.Count(),
                                           Total_Rooms_Booked = month.Sum(bookingTrans => bookingTrans.NOOFROOM),
                                           Total_SGD = month.Sum(
                                                                         bookingTrans => bookingTrans.PRICEPERROOM * bookingTrans.NOOFROOM * EntityFunctions.DiffDays(bookingTrans.STARTDATE, bookingTrans.ENDDATE)
                                                                      )
                                       });
                ViewData["Month"] = returnMonths.OrderByDescending(month => month.Total_SGD).ToList().Take(10);
            }
            catch (Exception e)
            {

            }
            try
            {
                var returnCountries = (from bookingTrans in _hotelEntity.BOOKING
                                    group bookingTrans by new { bookingTrans.H_COUNTRY } into country
                                    select new
                                    {
                                        Country = country.Key.H_COUNTRY,
                                        Number_Of_Hotels = (from hotel in _hotelEntity.HOTEL
                                                       where hotel.COUNTRY == country.Key.H_COUNTRY
                                                       select hotel).Count(),
                                        Total_Number_Of_Rooms = (from room in _hotelEntity.ROOM
                                                       where room.H_COUNTRY == country.Key.H_COUNTRY
                                                       select room.NOOFROOM).Sum(),
                                        Total_Number_Of_Bookings = country.Count(),
                                        Total_Rooms_Booked = country.Sum(bookingTrans => bookingTrans.NOOFROOM),
                                        Total_SGD = country.Sum(
                                                                      bookingTrans => bookingTrans.PRICEPERROOM * bookingTrans.NOOFROOM * EntityFunctions.DiffDays(bookingTrans.STARTDATE, bookingTrans.ENDDATE)
                                                                   )
                                    });
                ViewData["Country"] = returnCountries.OrderByDescending(country => country.Total_Number_Of_Bookings).ToList().Take(10);
            }
            catch (Exception e)
            {

            }
            try
            {
                var returnClients = (from bookingTrans in _hotelEntity.BOOKING
                                       group bookingTrans by new { bookingTrans.C_EMAIL } into client
                                       select new
                                       {
                                           Email = client.Key.C_EMAIL,
                                           Total_Number_Of_Bookings = client.Count(),
                                           Total_Rooms_Booked = client.Sum(bookingTrans => bookingTrans.NOOFROOM),
                                           Total_SGD = client.Sum(
                                                                         bookingTrans => bookingTrans.PRICEPERROOM * bookingTrans.NOOFROOM * EntityFunctions.DiffDays(bookingTrans.STARTDATE, bookingTrans.ENDDATE)
                                                                      )
                                       });
                ViewData["Client"] = returnClients.OrderByDescending(country => country.Total_SGD).ToList().Take(10);
            }
            catch (Exception e)
            {

            }
            return View();
        }
        public ActionResult About()
        {
            return RedirectToAction("Index");
        }
        //
        // GET: /MainSearch/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /MainSearch/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /MainSearch/Edit/5
        public ActionResult ListAllBooking()
        {
            string searchString = "@";
            var returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                         where transaction.C_EMAIL.ToLower().Contains(searchString)
                                         select new
                                         {
                                             ID = transaction.BOOKINGID,
                                             Email = transaction.C_EMAIL,
                                             Hotel_Name = transaction.H_BRANCHNAME,
                                             Country = transaction.H_COUNTRY,
                                             Start = transaction.STARTDATE,
                                             End = transaction.ENDDATE
                                         };
            ViewData["searchResult"] = returnTransactionEmail.OrderBy(transaction => transaction.ID).ToList();
            ViewData["resultType"] = "_transaction";
            return View();
        }
        public ActionResult ListAllClient()
        {
            string searchString = "@";
            var returnTransactionEmail = from client in _hotelEntity.CLIENT
                                         where client.EMAIL.ToLower().Contains(searchString)
                                         select new
                                         {
                                             Email = client.EMAIL,
                                             FirstName = client.FIRSTNAME,
                                             LastName = client.LASTNAME,
                                             Gender = client.GENDER,
                                             Contact = client.CONTACT,
                                             Country = client.COUNTRY,
                                             Passport = client.PASSPORTNO
                                         };
            ViewData["searchResult"] = returnTransactionEmail.OrderBy(client => client.Email).ToList();
            ViewData["resultType"] = "_client";
            return View();
        }
        public ActionResult ListAllHotel()
        {
            string searchString = " ";
            var returnHotelsCountry = from hotel in _hotelEntity.HOTEL
                                      where hotel.ADDRESS.ToLower().Contains(searchString.ToLower())
                                      select new
                                      {
                                          Hotel = hotel.HOTEL_NAME,
                                          Branch = hotel.BRANCHNAME,
                                          Country = hotel.COUNTRY,
                                          Address = hotel.ADDRESS,
                                          Contact = hotel.CONTACT
                                      };
            ViewData["searchResult"] = returnHotelsCountry.OrderBy(hotel => hotel.Hotel).ToList();
            ViewData["resultType"] = "_hotel";
            return View();
        }
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /MainSearch/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /MainSearch/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        public ActionResult AddRoomType(HOTEL hotel)
        {
            return Redirect("Index");
        }
        public ActionResult AddFacility(string hotel, string branch, string country)
        {
            return Redirect("Index");
        }
        public ActionResult DeleteHotel(HOTEL hotelToDelete)
        {
            return RedirectToAction("Index");
        }
        public ActionResult DeleteFacility(FACILITIES faciToDelete)
        {
            string messageResult = "";
            try
            {
                var objectToDelete = (from facility in _hotelEntity.FACILITIES
                                      where facility.H_BRANCHNAME.Contains(faciToDelete.H_BRANCHNAME)
                                            && facility.H_NAME.Contains(faciToDelete.H_NAME)
                                            && facility.H_COUNTRY.Contains(faciToDelete.H_COUNTRY)
                                            && facility.FACILITY.Contains(faciToDelete.FACILITY)
                                      select facility).First();
                _hotelEntity.DeleteObject(objectToDelete);
                _hotelEntity.SaveChanges();
                messageResult = "Successfully deleted \'" + faciToDelete.FACILITY + "\' facility from this hotel";
            }
            catch
            {
                messageResult = "Error deleting facility: \'" + faciToDelete.FACILITY + "\' from this hotel";
            }
            return RedirectToAction("ViewDetailsHotel",
                new
                {
                    hotelName = faciToDelete.H_NAME,
                    branchName = faciToDelete.H_BRANCHNAME,
                    country = faciToDelete.H_COUNTRY,
                    message = messageResult
                });
        }
        public ActionResult DeleteRoomType(ROOM roomToDelete)
        {
            string messageResult = "";
            try
            {
                var objectToDelete = (from room in _hotelEntity.ROOM
                                      where room.H_BRANCHNAME.Contains(roomToDelete.H_BRANCHNAME)
                                            && room.H_NAME.Contains(roomToDelete.H_NAME)
                                            && room.H_COUNTRY.Contains(roomToDelete.H_COUNTRY)
                                            && room.ROOMTYPE.Contains(roomToDelete.ROOMTYPE)
                                            && room.BEDTYPE.Contains(room.BEDTYPE)
                                      select room).First();
                _hotelEntity.DeleteObject(objectToDelete);
                _hotelEntity.SaveChanges();
                messageResult = "Successfully deleted \'" + roomToDelete.ROOMTYPE
                    + " - " + roomToDelete.BEDTYPE + "\' room type from this hotel";
            }
            catch
            {
                messageResult = "Error deleting room type: \'" + roomToDelete.ROOMTYPE
                    + " - " + roomToDelete.BEDTYPE + "\' from this hotel";
            }
            return RedirectToAction("ViewDetailsHotel",
                new
                {
                    hotelName = roomToDelete.H_NAME,
                    branchName = roomToDelete.H_BRANCHNAME,
                    country = roomToDelete.H_COUNTRY,
                    message = messageResult
                });
        }
        public ActionResult EditHotelInfo(HOTEL hotelToEdit)
        {
            return View();
        }
        [HttpPost]
        public ActionResult EditHotelInfo(HOTEL newHotel, HttpPostedFileBase file)
        {
            bool cancel = Request.Form.Get("Cancel") != null;
            if (cancel)
                return RedirectToAction("ViewDetailsHotel", new { hotelName = newHotel.HOTEL_NAME, branchName = newHotel.BRANCHNAME, country = newHotel.COUNTRY });
            string filename_with_path = "";
            bool file_uploaded = false;
            try
            {
                newHotel.HOTEL_NAME = toTitleCase(newHotel.HOTEL_NAME);
                newHotel.COUNTRY = toTitleCase(newHotel.COUNTRY);
                newHotel.BRANCHNAME = toTitleCase(newHotel.BRANCHNAME);
                newHotel.DISTRICT = toTitleCase(newHotel.DISTRICT);
                newHotel.ADDRESS = toTitleCase(newHotel.ADDRESS);
                //error checking
                int error_state = 0;
                if (string.IsNullOrWhiteSpace(newHotel.HOTEL_NAME))
                {
                    error_state++;
                    ViewData["NAME_ERROR"] = "Name is a required field";
                }
                if (string.IsNullOrWhiteSpace(newHotel.COUNTRY))
                {
                    error_state++;
                    ViewData["COUNTRY_ERROR"] = "Country is a required field";
                }
                if (string.IsNullOrWhiteSpace(newHotel.BRANCHNAME))
                {
                    error_state++;
                    ViewData["BRANCHNAME_ERROR"] = "Branch Name is a required field";
                }
                if (string.IsNullOrWhiteSpace(newHotel.DISTRICT))
                {
                    error_state++;
                    ViewData["DISTRICT_ERROR"] = "District is a required field";
                }
                if (string.IsNullOrWhiteSpace(newHotel.ADDRESS))
                {
                    error_state++;
                    ViewData["ADDRESS_ERROR"] = "Address is a required field";
                }
                string input = Request.Form.Get("CONTACT");
                if (string.IsNullOrWhiteSpace(input))
                {
                    error_state++;
                    ViewData["CONTACT_ERROR"] = "Contact is a required field";
                }
                else if (newHotel.CONTACT == 0)
                {
                    error_state++;
                    ViewData["CONTACT_ERROR"] = "Invalid Contact!";
                }

                error_state += checkLengthAndPopulateError(ViewData, newHotel.HOTEL_NAME, 80, "NAME_ERROR", "Name");
                error_state += checkLengthAndPopulateError(ViewData, newHotel.COUNTRY, 60, "COUNTRY_ERROR", "Country");
                error_state += checkLengthAndPopulateError(ViewData, newHotel.BRANCHNAME, 60, "BRANCHNAME_ERROR", "Branch");
                error_state += checkLengthAndPopulateError(ViewData, newHotel.DESCRIPTION, 512, "DESCRIPTION_ERROR", "Description");
                error_state += checkLengthAndPopulateError(ViewData, newHotel.ADDRESS, 255, "ADDRESS_ERROR", "Address");
                error_state += checkLengthAndPopulateError(ViewData, newHotel.DISTRICT, 60, "DISTRICT_ERROR", "District");
                if (error_state > 0)
                {
                    return View(newHotel);
                }
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    filename_with_path = Path.Combine(Server.MapPath("~/Content"), fileName);

                    var directory = Path.GetDirectoryName(filename_with_path);
                    var filename_without_extension = Path.GetFileNameWithoutExtension(filename_with_path);
                    var extension = Path.GetExtension(filename_with_path);

                    int i = 0;
                    while (System.IO.File.Exists(filename_with_path))
                    {
                        i++;
                        fileName = filename_without_extension + i.ToString() + extension;
                        filename_with_path = Path.Combine(directory, fileName);
                    }

                    file.SaveAs(filename_with_path);
                    file_uploaded = true;

                    var relative_path = "/Content/" + fileName;
                    newHotel.HOTELIMAGE = relative_path;
                }
                var hotelToEdit = (from Hotel in _hotelEntity.HOTEL
                                   where Hotel.HOTEL_NAME == newHotel.HOTEL_NAME &&
                                   Hotel.COUNTRY == newHotel.COUNTRY &&
                                   Hotel.BRANCHNAME == newHotel.BRANCHNAME
                                   select Hotel).First();
                hotelToEdit.DESCRIPTION = newHotel.DESCRIPTION;
                hotelToEdit.HOTELIMAGE = newHotel.HOTELIMAGE;
                hotelToEdit.ADDRESS = newHotel.ADDRESS;
                hotelToEdit.CONTACT = newHotel.CONTACT;
                hotelToEdit.DISTRICT = newHotel.DISTRICT;
                hotelToEdit.SERVICELEVEL = newHotel.SERVICELEVEL;
                _hotelEntity.SaveChanges();
                return RedirectToAction("ViewDetailsHotel", new { hotelName = newHotel.HOTEL_NAME, branchName = newHotel.BRANCHNAME, country = newHotel.COUNTRY });
            }
            catch (System.Web.HttpException e)
            {
                ViewData["ERROR"] = "An error has occurred during uploading of the image!";
                if (file_uploaded && System.IO.File.Exists(filename_with_path))
                {
                    System.IO.File.Delete(filename_with_path);
                }
                return View(newHotel);
            }
            catch
            {
                ViewData["ERROR"] = "An unknown error has occurred! Please try again later.";
                if (file_uploaded && System.IO.File.Exists(filename_with_path))
                {
                    System.IO.File.Delete(filename_with_path);
                }
                return View(newHotel);
            }
        }
        public ActionResult EditFacility(FACILITIES newFacility, HttpPostedFileBase file)
        {
            bool cancel = Request.Form.Get("Cancel") != null;
            if (cancel)
                return RedirectToAction("ViewDetailsHotel", new { hotelName = newFacility.H_NAME, branchName = newFacility.H_BRANCHNAME, country = newFacility.H_COUNTRY});
            string filename_with_path = "";
            bool file_uploaded = false;
            try
            {
                newFacility.FACILITY = toTitleCase(newFacility.FACILITY);
                //error checking
                SelectList hotel_names;
                SelectList branch_names;
                SelectList country_names;
                string ctrlname = Request.Params.Get("__EVENTTARGET");
                bool submit = Request.Form.Get("save") != null;
                if (!submit)           //postback not due to submit button
                {
                    hotel_names = getHotelNames(newFacility.H_NAME);
                    ViewData["hotel_names"] = hotel_names;

                    string hotel_name = hotel_names.First().Text;
                    if (newFacility.H_NAME != null)
                    {
                        hotel_name = newFacility.H_NAME;
                    }
                    country_names = getCountryNames(hotel_name);

                    ViewData["country_names"] = country_names;

                    string country_name = country_names.First().Text;

                    foreach (SelectListItem s in country_names)
                    {
                        if (string.Compare(s.Text, newFacility.H_COUNTRY, true) == 0)
                        {
                            country_name = s.Text;
                            break;
                        }
                    }
                    newFacility.H_COUNTRY = country_name;


                    branch_names = getBranchNames(hotel_name, country_name);
                    ViewData["branch_names"] = branch_names;
                    return View(newFacility);
                }
                else                                    //postback due to submit button
                {
                    int error_state = 0;
                    if (string.IsNullOrWhiteSpace(newFacility.FACILITY))
                    {
                        error_state++;
                        ViewData["FACILITY_ERROR"] = "Facility Type is a required field";
                    }
                    if (newFacility.FACILITY != null && newFacility.H_NAME != null && newFacility.H_COUNTRY != null && newFacility.H_BRANCHNAME != null)
                    {


                    }
                    error_state += checkLengthAndPopulateError(ViewData, newFacility.FACILITY, 80, "FACILITY_ERROR", "Facility");
                    error_state += checkLengthAndPopulateError(ViewData, newFacility.DESCRIPTION, 512, "DESCRIPTION_ERROR", "Description");
                    if (error_state > 0)
                    {
                        populateHotelListForDropDownList(ViewData, newFacility.H_NAME, newFacility.H_COUNTRY, newFacility.H_BRANCHNAME);
                        return View(newFacility);
                    }
                    if (file != null && file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        filename_with_path = Path.Combine(Server.MapPath("~/Content"), fileName);

                        var directory = Path.GetDirectoryName(filename_with_path);
                        var filename_without_extension = Path.GetFileNameWithoutExtension(filename_with_path);
                        var extension = Path.GetExtension(filename_with_path);

                        int i = 0;
                        while (System.IO.File.Exists(filename_with_path))
                        {
                            i++;
                            fileName = filename_without_extension + i.ToString() + extension;
                            filename_with_path = Path.Combine(directory, fileName);
                        }

                        file.SaveAs(filename_with_path);
                        file_uploaded = true;

                        var relative_path = "/Content/" + fileName;
                        newFacility.FACILITYIMAGE = relative_path;
                    }
                    var facilityToEdit = (from Facility in _hotelEntity.FACILITIES
                                     where Facility.H_NAME == newFacility.H_NAME &&
                                     Facility.H_COUNTRY == newFacility.H_COUNTRY &&
                                     Facility.H_BRANCHNAME == newFacility.H_BRANCHNAME &&
                                     Facility.FACILITY == newFacility.FACILITY
                                     select Facility).First();
                    facilityToEdit.DESCRIPTION = newFacility.DESCRIPTION;
                    facilityToEdit.FACILITYIMAGE = newFacility.FACILITYIMAGE;
                    _hotelEntity.SaveChanges();
                    return RedirectToAction("../AdminMain/ViewDetailsHotel", new { hotelName = newFacility.H_NAME, branchName = newFacility.H_BRANCHNAME, country = newFacility.H_COUNTRY });
                }
            }
            catch (System.Web.HttpException e)
            {
                ViewData["ERROR"] = "An error has occurred during uploading of the image!";
                if (file_uploaded && System.IO.File.Exists(filename_with_path))
                {
                    System.IO.File.Delete(filename_with_path);
                }
                populateHotelListForDropDownList(ViewData, newFacility.H_NAME, newFacility.H_COUNTRY, newFacility.H_BRANCHNAME);
                return View(newFacility);
            }
            catch
            {
                ViewData["ERROR"] = "An unknown error has occurred! Please try again later.";
                if (file_uploaded && System.IO.File.Exists(filename_with_path))
                {
                    System.IO.File.Delete(filename_with_path);
                }
                populateHotelListForDropDownList(ViewData, newFacility.H_NAME, newFacility.H_COUNTRY, newFacility.H_BRANCHNAME);
                return View(newFacility);
            }
        }

        public ActionResult EditRoomType(ROOM roomTypeToEdit)
        {
            return View();
        }
        [HttpPost]
        public ActionResult EditRoomType(ROOM roomTypeToEdit, HttpPostedFileBase file)
        {
            string filename_with_path = "";
            bool file_uploaded = false;
            try
            {
                roomTypeToEdit.ROOMTYPE = toTitleCase(roomTypeToEdit.ROOMTYPE);
                roomTypeToEdit.BEDTYPE = toTitleCase(roomTypeToEdit.BEDTYPE);
                roomTypeToEdit.DIRECTION = toTitleCase(roomTypeToEdit.DIRECTION);

                SelectList hotel_names;
                SelectList branch_names;
                SelectList country_names;
                string ctrlname = Request.Params.Get("__EVENTTARGET");
                bool cancel = Request.Form.Get("Cancel") != null;
                if (cancel)
                    return RedirectToAction("ViewDetailsHotel", new { hotelName = roomTypeToEdit.H_NAME, branchName = roomTypeToEdit.H_BRANCHNAME, country = roomTypeToEdit.H_COUNTRY });

                bool submit = Request.Form.Get("save") != null;
                if (!submit)           //postback not due to submit button
                {
                    hotel_names = getHotelNames(roomTypeToEdit.H_NAME);
                    ViewData["hotel_names"] = hotel_names;

                    string hotel_name = hotel_names.First().Text;
                    if (roomTypeToEdit.H_NAME != null)
                    {
                        hotel_name = roomTypeToEdit.H_NAME;
                    }
                    country_names = getCountryNames(hotel_name);

                    ViewData["country_names"] = country_names;

                    string country_name = country_names.First().Text;

                    foreach (SelectListItem s in country_names)
                    {
                        if (string.Compare(s.Text, roomTypeToEdit.H_COUNTRY, true) == 0)
                        {
                            country_name = s.Text;
                            break;
                        }
                    }
                    roomTypeToEdit.H_COUNTRY = country_name;


                    branch_names = getBranchNames(hotel_name, country_name);
                    ViewData["branch_names"] = branch_names;
                    return View(roomTypeToEdit);
                }
                else                                    //postback due to submit button
                {
                    int error_state = 0;
                    if (string.IsNullOrWhiteSpace(roomTypeToEdit.ROOMTYPE))
                    {
                        error_state++;
                        ViewData["ROOMTYPE_ERROR"] = "Room Type is a required field";
                    }
                    if (string.IsNullOrWhiteSpace(roomTypeToEdit.BEDTYPE))
                    {
                        error_state++;
                        ViewData["BEDTYPE_ERROR"] = "Bed Type is a required field";
                    }
                    if (roomTypeToEdit.PRICE == null)
                    {
                        error_state++;
                        ViewData["PRICE_ERROR"] = "Price is a required field";
                    }
                    if (roomTypeToEdit.PRICE == 0)
                    {
                        error_state++;
                        ViewData["PRICE_ERROR"] = "Price cannot be 0!";
                    }
                    string input = Request.Form.Get("PRICE");
                    if (!string.IsNullOrWhiteSpace(input) && roomTypeToEdit.PRICE == null)
                    {
                        error_state++;
                        ViewData["PRICE_ERROR"] = "Invalid Price! Please enter numerical values only!";
                    }
                    input = Request.Form.Get("NOOFROOM");
                    if (!string.IsNullOrWhiteSpace(input) && (roomTypeToEdit.NOOFROOM == 0 || roomTypeToEdit.NOOFROOM == null))
                    {
                        error_state++;
                        ViewData["NOOFROOM_ERROR"] = "Invalid Number of Rooms! Please enter numerical values only!";
                    }
                    if (roomTypeToEdit.H_NAME != null && roomTypeToEdit.H_COUNTRY != null && roomTypeToEdit.H_BRANCHNAME != null && roomTypeToEdit.ROOMTYPE != null && roomTypeToEdit.BEDTYPE != null)
                    {


                    }
                    error_state += checkLengthAndPopulateError(ViewData, roomTypeToEdit.DIRECTION, 255, "DIRECTION_ERROR", "Direction");
                    error_state += checkLengthAndPopulateError(ViewData, roomTypeToEdit.ROOMTYPE, 60, "ROOMTYPE_ERROR", "Room Type");
                    error_state += checkLengthAndPopulateError(ViewData, roomTypeToEdit.BEDTYPE, 20, "BEDTYPE_ERROR", "Bed Type");
                    error_state += checkLengthAndPopulateError(ViewData, roomTypeToEdit.DESCRIPTION, 512, "DESCRIPTION_ERROR", "Description");
                    if (error_state > 0)
                    {
                        populateHotelListForDropDownList(ViewData, roomTypeToEdit.H_NAME, roomTypeToEdit.H_COUNTRY, roomTypeToEdit.H_BRANCHNAME);
                        return View(roomTypeToEdit);
                    }
                    if (file != null && file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        filename_with_path = Path.Combine(Server.MapPath("~/Content"), fileName);

                        var directory = Path.GetDirectoryName(filename_with_path);
                        var filename_without_extension = Path.GetFileNameWithoutExtension(filename_with_path);
                        var extension = Path.GetExtension(filename_with_path);

                        int i = 0;
                        while (System.IO.File.Exists(filename_with_path))
                        {
                            i++;
                            fileName = filename_without_extension + i.ToString() + extension;
                            filename_with_path = Path.Combine(directory, fileName);
                        }

                        file.SaveAs(filename_with_path);
                        file_uploaded = true;

                        var relative_path = "/Content/" + fileName;
                        roomTypeToEdit.ROOMIMAGE = relative_path;
                    }
                    var roomToEdit = (from Room in _hotelEntity.ROOM
                               where Room.H_NAME == roomTypeToEdit.H_NAME &&
                               Room.H_COUNTRY == roomTypeToEdit.H_COUNTRY &&
                               Room.H_BRANCHNAME == roomTypeToEdit.H_BRANCHNAME &&
                               Room.ROOMTYPE == roomTypeToEdit.ROOMTYPE &&
                               Room.BEDTYPE == roomTypeToEdit.BEDTYPE
                               select Room).First();
                   
                    roomToEdit.PRICE = roomTypeToEdit.PRICE;
                    roomToEdit.DIRECTION = roomTypeToEdit.DIRECTION;
                    roomToEdit.NOOFROOM = roomTypeToEdit.NOOFROOM;
                    roomToEdit.DESCRIPTION = roomTypeToEdit.DESCRIPTION;
                    roomToEdit.ROOMIMAGE = roomTypeToEdit.ROOMIMAGE;
                    _hotelEntity.SaveChanges();
                    return RedirectToAction("../AdminMain/ViewDetailsHotel", new { hotelName = roomTypeToEdit.H_NAME, branchName = roomTypeToEdit.H_BRANCHNAME, country = roomTypeToEdit.H_COUNTRY });
                }
            }
            catch (System.Web.HttpException e)
            {
                ViewData["ERROR"] = "An error has occurred during uploading of the image!";
                if (file_uploaded && System.IO.File.Exists(filename_with_path))
                {
                    System.IO.File.Delete(filename_with_path);
                }
                populateHotelListForDropDownList(ViewData, roomTypeToEdit.H_NAME, roomTypeToEdit.H_COUNTRY, roomTypeToEdit.H_BRANCHNAME);
                return View(roomTypeToEdit);
            }
            catch
            {
                ViewData["ERROR"] = "An unknown error has occurred! Please try again later.";
                if (file_uploaded && System.IO.File.Exists(filename_with_path))
                {
                    System.IO.File.Delete(filename_with_path);
                }
                populateHotelListForDropDownList(ViewData, roomTypeToEdit.H_NAME, roomTypeToEdit.H_COUNTRY, roomTypeToEdit.H_BRANCHNAME);
                return View(roomTypeToEdit);
            }
            return RedirectToAction("Index");
        }
        public ActionResult BookingDetail(decimal id)
        {
            // Get movie to update
            if (!ChkValidUser())
                return RedirectToAction("Index", "Home");
            var transaction = _hotelEntity.BOOKING.First(m => m.BOOKINGID == id);

            ViewData.Model = transaction;
            return View();
        }
        public ActionResult EditBooking(decimal id)
        {
            // Get movie to update
            var transaction = _hotelEntity.BOOKING.First(m => m.BOOKINGID == id);
            var roomType = new SelectList(from rm in _hotelEntity.ROOM
                                          where rm.H_NAME == transaction.H_NAME
                                          && rm.H_BRANCHNAME == transaction.H_BRANCHNAME
                                          && rm.H_COUNTRY == transaction.H_COUNTRY
                                          select new SelectListItem
                                          {
                                              Text = rm.ROOMTYPE,
                                              Value = rm.ROOMTYPE
                                          }, "Value", "Text", transaction.R_ROOMTYPE);
            SelectList bedType = new SelectList(from rm in _hotelEntity.ROOM
                                                where rm.H_NAME == transaction.H_NAME
                                                && rm.H_BRANCHNAME == transaction.H_BRANCHNAME
                                                && rm.H_COUNTRY == transaction.H_COUNTRY
                                                && rm.ROOMTYPE == transaction.R_ROOMTYPE
                                                select new SelectListItem
                                                {
                                                    Text = rm.BEDTYPE,
                                                    Value = rm.BEDTYPE
                                                }, "Value", "Text", transaction.R_BEDTYPE);
            ViewData.Model = transaction;
            ViewData["room"] = roomType;
            ViewData["bed"] = bedType;
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditBooking(FormCollection form)
        {

            try
            {
                if (!ChkValidUser())
                    return RedirectToAction("Index", "Home");
                if (string.IsNullOrEmpty(form["save"]))
                {
                    var raw = form["BOOKINGID"];
                    string[] raw1 = raw.Split(',');
                    var id = decimal.Parse(raw1[0]);
                    bool cancel = Request.Form.Get("Cancel") != null;
                    if (cancel)
                        return RedirectToAction("BookingDetail", new { id = id });
           
                    var book = _hotelEntity.BOOKING.First(m => m.BOOKINGID == id);
                    var startDate = form.Get("STARTDATE");
                    book.STARTDATE = DateTime.ParseExact(startDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    var endDate = form.Get("ENDDATE");
                    book.ENDDATE = DateTime.ParseExact(endDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    TryUpdateModel(book, new string[] { "C_EMAIL", "H_NAME", "H_BRANCHNAME", "H_COUNTRY", "R_ROOMTYPE", "BOOKINGID", "R_BEDTYPE", "NOOFROOM", "PRICEPERROOM" }, form.ToValueProvider());
                    var roomType = new SelectList(from rm in _hotelEntity.ROOM
                                                  where rm.H_NAME == book.H_NAME
                                                  && rm.H_BRANCHNAME == book.H_BRANCHNAME
                                                  && rm.H_COUNTRY == book.H_COUNTRY
                                                  select new SelectListItem
                                                  {
                                                      Text = rm.ROOMTYPE,
                                                      Value = rm.ROOMTYPE
                                                  }, "Value", "Text", book.R_ROOMTYPE);
                    SelectList bedType = new SelectList(from rm in _hotelEntity.ROOM
                                                        where rm.H_NAME == book.H_NAME
                                                        && rm.H_BRANCHNAME == book.H_BRANCHNAME
                                                        && rm.H_COUNTRY == book.H_COUNTRY
                                                        && rm.ROOMTYPE == book.R_ROOMTYPE
                                                        select new SelectListItem
                                                        {
                                                            Text = rm.BEDTYPE,
                                                            Value = rm.BEDTYPE
                                                        }, "Value", "Text", book.R_BEDTYPE);
                    var chk = (from rm in _hotelEntity.ROOM
                               where rm.H_NAME == book.H_NAME
                               && rm.H_BRANCHNAME == book.H_BRANCHNAME
                               && rm.H_COUNTRY == book.H_COUNTRY
                               && rm.ROOMTYPE == book.R_ROOMTYPE
                               && rm.BEDTYPE == book.R_BEDTYPE
                               select rm).Count();
                    Boolean chk2 = false;
                    if ((book.STARTDATE > book.ENDDATE))
                    {
                        ModelState.AddModelError("STARTDATE", "Arrival Date cannot be after departure date");
                        chk2 = true;
                    }
                    int numDaysDiff = Math.Abs(book.STARTDATE.Subtract(book.ENDDATE).Days);
                    if (numDaysDiff <= 0)
                    {
                        ModelState.AddModelError("ENDDATE", "Cannot book a room that departure today");
                        chk2 = true;
                    }
                    if (chk > 0 && chk2 == false)
                    {
                        book.PRICEPERROOM = decimal.Parse((from rm in _hotelEntity.ROOM
                                                           where rm.H_NAME == book.H_NAME
                                                           && rm.H_BRANCHNAME == book.H_BRANCHNAME
                                                           && rm.H_COUNTRY == book.H_COUNTRY
                                                           && rm.ROOMTYPE == book.R_ROOMTYPE
                                                           && rm.BEDTYPE == book.R_BEDTYPE
                                                           select rm.PRICE).First().ToString());
                    }
                    else
                    {
                        ModelState.AddModelError("R_BEDTYPE", "Require to select a room type");
                        book.PRICEPERROOM = 0;
                    }
                    if (book.NOOFROOM == 0)
                    {
                        ModelState.AddModelError("NOOFROOM", "Require to book at least 1 room");
                    }
                    if (string.IsNullOrEmpty(book.R_BEDTYPE))
                    {
                        ModelState.AddModelError("R_BEDTYPE", "Require to select a room type");
                    }
                    ViewData["room"] = roomType;
                    ViewData["bed"] = bedType;
                    return View(book);

                }
                else
                {

                    var raw = form["BOOKINGID"];
                    string[] raw1 = raw.Split(',');
                    var id = decimal.Parse(raw1[0]);
                    var book = _hotelEntity.BOOKING.First(m => m.BOOKINGID == id);
                    var startDate = form.Get("STARTDATE");
                    book.STARTDATE = DateTime.ParseExact(startDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    var endDate = form.Get("ENDDATE");
                    book.ENDDATE = DateTime.ParseExact(endDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    TryUpdateModel(book, new string[] { "C_EMAIL", "H_NAME", "H_BRANCHNAME", "H_COUNTRY", "R_ROOMTYPE", "BOOKINGID", "R_BEDTYPE", "NOOFROOM", "PRICEPERROOM" }, form.ToValueProvider());

                    Boolean chk2 = false;
                    if ((book.STARTDATE > book.ENDDATE))
                    {
                        ModelState.AddModelError("STARTDATE", "Arrival Date cannot be after departure date");
                        chk2 = true;
                    }
                    int numDaysDiff = Math.Abs(book.STARTDATE.Subtract(book.ENDDATE).Days);
                    if (numDaysDiff <= 0)
                    {
                        ModelState.AddModelError("ENDDATE", "Cannot book a room that departure today");
                        chk2 = true;
                    }
                    if (!string.IsNullOrEmpty(book.BOOKINGID.ToString()) && !string.IsNullOrEmpty(book.H_NAME) && !string.IsNullOrEmpty(book.H_COUNTRY) && !string.IsNullOrEmpty(book.H_BRANCHNAME) && chk2 == false && !string.IsNullOrEmpty(book.R_BEDTYPE) && !string.IsNullOrEmpty(book.R_ROOMTYPE))
                    {
                        _hotelEntity.SaveChanges();
                    }
                    else
                    {

                        if (book.NOOFROOM == 0)
                        {
                            ModelState.AddModelError("NOOFROOM", "Require to book at least 1 room");
                        }
                        if (string.IsNullOrEmpty(book.R_ROOMTYPE))
                        {
                            ModelState.AddModelError("R_ROOMTYPE", "Require to select a room type");
                        }
                        if (string.IsNullOrEmpty(book.R_BEDTYPE))
                        {
                            ModelState.AddModelError("R_BEDTYPE", "Require to select a Bed type");
                        }
                        var roomType = new SelectList(from rm in _hotelEntity.ROOM
                                                      where rm.H_NAME == book.H_NAME
                                                      && rm.H_BRANCHNAME == book.H_BRANCHNAME
                                                      && rm.H_COUNTRY == book.H_COUNTRY
                                                      select new SelectListItem
                                                      {
                                                          Text = rm.ROOMTYPE,
                                                          Value = rm.ROOMTYPE
                                                      }, "Value", "Text", book.R_ROOMTYPE);
                        SelectList bedType = new SelectList(from rm in _hotelEntity.ROOM
                                                            where rm.H_NAME == book.H_NAME
                                                            && rm.H_BRANCHNAME == book.H_BRANCHNAME
                                                            && rm.H_COUNTRY == book.H_COUNTRY
                                                            && rm.ROOMTYPE == book.R_ROOMTYPE
                                                            select new SelectListItem
                                                            {
                                                                Text = rm.BEDTYPE,
                                                                Value = rm.BEDTYPE
                                                            }, "Value", "Text");
                        ViewData["room"] = roomType;
                        ViewData["bed"] = bedType;
                        return View(book);
                    }
                    return RedirectToAction("BookingDetail", new { id = id });
                }
            }
            catch
            {
                return RedirectToAction("Error", "Home");
            }
        }
        public ActionResult EditClientInfo(CLIENT newClient)
        {
            return View();
        }
        [HttpPost]
        public ActionResult EditClientInfo(FormCollection form)
        {
            CLIENT user = new CLIENT();
            string contact = form.Get("CONTACT");
            // Deserialize (Include white list!)
            TryUpdateModel(user, new string[] { "Email", "PWD", "COUNTRY", "DESIGNATION", "FIRSTNAME", "LASTNAME", "PASSPORTNO", "GENDER", "ADDRESS", "CONTACT" }, form.ToValueProvider());
            bool cancel = Request.Form.Get("Cancel") != null;
            if (cancel)
                return RedirectToAction("ViewDetailsClient", new { userEmail = user.EMAIL });
           
            user.ACCOUNTSTATUS = "member";
            // Validate
            ValidateEmail(user.EMAIL);
            ValidatePWD(user.PWD);
            ValidateAddress(user.ADDRESS);
            ValidateCountry(user.COUNTRY);
            ValidateName(user.DESIGNATION, user.FIRSTNAME, user.LASTNAME);
            ValidatePassport(user.PASSPORTNO);
            ValidateGender(user.GENDER);
            ValidateContact(contact);

            // If valid, save movie to database
            if (ModelState.IsValid)
            {
                var clienToEdit = (from client in _hotelEntity.CLIENT
                                   where client.EMAIL == user.EMAIL
                                   select client).First();
                clienToEdit.PWD = user.PWD;
                clienToEdit.FIRSTNAME = user.FIRSTNAME;
                clienToEdit.LASTNAME = user.LASTNAME;
                clienToEdit.DESIGNATION = user.DESIGNATION;
                clienToEdit.PASSPORTNO = user.PASSPORTNO;
                clienToEdit.GENDER = user.GENDER;
                clienToEdit.ADDRESS = user.ADDRESS;
                clienToEdit.CONTACT = user.CONTACT;
                clienToEdit.COUNTRY = user.COUNTRY;
                _hotelEntity.SaveChanges();
                return RedirectToAction("ViewDetailsClient", new { userEmail = user.EMAIL });
            }

            // Otherwise, reshow form
            return View(user);
        }
        public object ViewDetails(string type, string key1, string key2, string key3)
        {
            switch (type) //value of radiobuttonList
            {
                case "_hotel":
                    return RedirectToAction("ViewDetailsHotel", new { hotelName = key1, branchName = key2, country = key3 });
                case "_client":
                    return RedirectToAction("ViewDetailsClient", new { userEmail = key1 });
                //return RedirectToAction("SearchClient", new { dropList = resultDropList, searchString = searchString, sizeOfTable = 11 });
                case "_transaction":
                    return RedirectToAction("BookingDetail", new { id = key1 });
                default:
                    return RedirectToAction("Index");
            }
        }

        public object ViewDetailsHotel(string hotelName, string branchName, string country, string message)
        {
            var resultHotel = viewHotel(hotelName, branchName, country);
            ROOM[] roomList = viewRoomList(hotelName, branchName, country);
            FACILITIES[] faciList = viewFacilityList(hotelName, branchName, country);

            if (resultHotel == null)
            {
                ViewData["hotelModel"] = "";
            }
            else
            {
                ViewData["hotelModel"] = resultHotel;
            }

            if (roomList == null)
            {
                ViewData["roomListModel"] = "";
            }
            else
            {
                for (int count = 0; count < roomList.Count(); count++)
                {
                    ViewData["roomListModel" + count] = roomList.ElementAt(count);
                }
                ViewData["numberOfRoomTypes"] = roomList.Count();
            }
            if (faciList == null)
            {
                ViewData["faciListModel"] = "";
            }
            else
            {
                for (int count = 0; count < faciList.Count(); count++)
                {
                    ViewData["faciListModel" + count] = faciList.ElementAt(count);
                }
                ViewData["numberOfFacilities"] = faciList.Count();
            }
            ViewData["ResultMessage"] = message;
            return View();
        }

        private object viewHotel(string hotelName, string branchName, string country)
        {
            try
            {
                var hotelReturnList = (from hotel in _hotelEntity.HOTEL
                                       where hotel.BRANCHNAME.Equals(branchName)
                                             && hotel.HOTEL_NAME.Equals(hotelName)
                                             && hotel.COUNTRY.Equals(country)
                                       select hotel);
                return hotelReturnList.First();
            }
            catch
            {
                return null;
            }

        }
        private ROOM[] viewRoomList(string hotelName, string branchName, string country)
        {
            try
            {
                var roomReturnList = (from room in _hotelEntity.ROOM
                                      where room.H_BRANCHNAME.Equals(branchName)
                                             && room.H_NAME.Equals(hotelName)
                                             && room.H_COUNTRY.Equals(country)
                                      select room);
                return roomReturnList.ToArray();
            }
            catch
            {
                return null;
            }
        }
        private FACILITIES[] viewFacilityList(string hotelName, string branchName, string country)
        {
            try
            {
                var facilityReturnList = (from faci in _hotelEntity.FACILITIES
                                          where faci.H_BRANCHNAME.Equals(branchName)
                                             && faci.H_NAME.Equals(hotelName)
                                             && faci.H_COUNTRY.Equals(country)
                                          select faci);
                return facilityReturnList.ToArray();
            }
            catch
            {
                return null;
            }
        }
        public ActionResult MainSearch()
        {
            return View();
        }
        public ActionResult Search(FormCollection form)
        {
            string sortBy = "Hotel";
            if (form["__EVENTTARGET"] != null && form["__EVENTTARGET"].ToString().Count() != 0)
            {
                sortBy = form["__EVENTARGUMENT"].Substring(5);
            }
            int resultCount = 0;
            ViewData["resultType"] = "_hotel"; //set default
            ViewData["searchString"] = "";
            ViewData["searchCriteria"] = "";
            ViewData["startDate"] = ViewData["endDate"] = "";
            try{
                String radioButtonResult = form["radioButtonListMainSearch"].ToString();
                ViewData["searchString"] = form["searchString"].ToString();
                ViewData["resultType"] = radioButtonResult;

                switch (radioButtonResult) //value of radiobuttonList
                {
                    case "_hotel":
                        ViewData["searchCriteria"] = form["ctl00$MainContent$dropdownlistSearchHotelCriteria"].ToString();
                        var listOfHotel = SearchHotel(ref form, ref resultCount, sortBy);
                        if (listOfHotel == null)
                        {
                            ViewData["Message"] = "No Result Found!";
                            ViewData["searchResult"] = "";
                        }
                        else
                        {
                            ViewData["Message"] = resultCount + " results found";
                            ViewData["searchResult"] = listOfHotel;
                        }
                        return View(form);
                    case "_client":
                        ViewData["searchCriteria"] = form["ctl00$MainContent$dropdownlistSearchClientCriteria"].ToString();
                        var listOfClient = SearchClient(ref form, ref resultCount, sortBy);
                        if (listOfClient == null)
                        {
                            ViewData["Message"] = "No Result Found!";
                            ViewData["searchResult"] = "";
                        }
                        else
                        {
                            ViewData["Message"] = resultCount + " results found";
                            ViewData["searchResult"] = listOfClient;
                        }
                        return View();

                    case "_transaction":
                        ViewData["searchCriteria"] = form["ctl00$MainContent$dropdownlistSearchBookingCriteria"].ToString();
                        var listOfTransaction = SearchTransaction(ref form, ref resultCount, sortBy);
                        if (listOfTransaction == null)
                        {
                            ViewData["Message"] = "No Result Found!";
                            ViewData["searchResult"] = "";
                        }
                        else
                        {
                            ViewData["Message"] = resultCount + " results found";
                            ViewData["searchResult"] = listOfTransaction;
                        }
                        return View();
                    default:
                        return View();
                }
             }catch(Exception e){
                   return View();
             }
        }

        public object SearchHotel(ref FormCollection form, ref int resultCount, string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchHotelCriteria"].ToString();
            var searchString = form["searchString"]; 
            switch (searchCriteria) //value of radiobuttonList
            {
                case "_name":
                    return searchHotelByName(ref form, ref resultCount, sortBy);
                case "_address":
                    return searchHotelByAddress(ref form, ref resultCount, sortBy);
                case "_country":
                    return searchHotelByCountry(ref form, ref resultCount, sortBy);
                default:
                    return RedirectToAction("Index");
            }
        }

        private object searchHotelByCountry(ref FormCollection form, ref int resultCount, string sortBy)
        {
            var searchString = form["searchString"];
            var returnHotelsCountry = from hotel in _hotelEntity.HOTEL
                                      where hotel.COUNTRY.ToLower().Contains(searchString.ToLower())
                                      select new
                                      {
                                          Hotel = hotel.HOTEL_NAME,
                                          Branch = hotel.BRANCHNAME,
                                          Country = hotel.COUNTRY,
                                          Address = hotel.ADDRESS,
                                          Contact = hotel.CONTACT
                                      };
            if (returnHotelsCountry.ToList().Count == 0)
            {
                return null;
            }
            else
            {
                resultCount = returnHotelsCountry.ToList().Count;
                switch (sortBy)
                {
                    case "Hotel":
                    default:
                        return returnHotelsCountry.OrderBy(hotel => hotel.Hotel).ToList();
                    case "Branch":
                        return returnHotelsCountry.OrderBy(hotel => hotel.Branch).ToList();
                    case "Country":
                        return returnHotelsCountry.OrderBy(hotel => hotel.Country).ToList();
                    case "Address":
                        return returnHotelsCountry.OrderBy(hotel => hotel.Address).ToList();
                    case "Contact":
                        return returnHotelsCountry.OrderBy(hotel => hotel.Contact).ToList();
                }
            }
        }

        private object searchHotelByAddress(ref FormCollection form, ref int resultCount, string sortBy)
        {
            var searchString = form["searchString"];
            var returnHotelsAddress = from hotel in _hotelEntity.HOTEL
                                      where hotel.ADDRESS.ToLower().Contains(searchString.ToLower())
                                      select new
                                      {
                                          Hotel = hotel.HOTEL_NAME,
                                          Branch = hotel.BRANCHNAME,
                                          Country = hotel.COUNTRY,
                                          Address = hotel.ADDRESS,
                                          Contact = hotel.CONTACT
                                      };
            if (returnHotelsAddress.ToList().Count == 0)
            {
                return null;
            }
            else
            {
                resultCount = returnHotelsAddress.ToList().Count;
                switch (sortBy)
                {
                    case "Hotel":
                    default:
                        return returnHotelsAddress.OrderBy(hotel => hotel.Hotel).ToList();
                    case "Branch":
                        return returnHotelsAddress.OrderBy(hotel => hotel.Branch).ToList();
                    case "Country":
                        return returnHotelsAddress.OrderBy(hotel => hotel.Country).ToList();
                    case "Address":
                        return returnHotelsAddress.OrderBy(hotel => hotel.Address).ToList();
                    case "Contact":
                        return returnHotelsAddress.OrderBy(hotel => hotel.Contact).ToList();
                }
            }
        }

        private object searchHotelByName(ref FormCollection form, ref int resultCount, string sortBy)
        {
            var searchString = form["searchString"];
            var returnHotelsName = from hotel in _hotelEntity.HOTEL
                                           where hotel.HOTEL_NAME.ToLower().Contains(searchString.ToLower())
                                           orderby "Country" ascending
                                           select new
                                           {
                                               Hotel = hotel.HOTEL_NAME,
                                               Branch = hotel.BRANCHNAME,
                                               Country = hotel.COUNTRY,
                                               Address = hotel.ADDRESS,
                                               Contact = hotel.CONTACT
                                           };
                    if (returnHotelsName.ToList().Count == 0)
                    {
                        return null;
                    }
                    else
                    {
                        resultCount = returnHotelsName.ToList().Count;
                        switch (sortBy)
                        {
                            case "Hotel":
                            default:
                                return returnHotelsName.OrderBy(hotel => hotel.Hotel).ToList();
                            case "Branch":
                                return returnHotelsName.OrderBy(hotel => hotel.Branch).ToList();
                            case "Country":
                                return returnHotelsName.OrderBy(hotel => hotel.Country).ToList();
                            case "Address":
                                return returnHotelsName.OrderBy(hotel => hotel.Address).ToList();
                            case "Contact":
                                return returnHotelsName.OrderBy(hotel => hotel.Contact).ToList();
                        }
                    }
        }
        private string toTitleCase(string str)
        {
            if (str != null)
            {
                System.Globalization.TextInfo txtInfo = new System.Globalization.CultureInfo("en-US", false).TextInfo;
                str = txtInfo.ToTitleCase(str);
            }
            return str;
        }
        private int checkLengthAndPopulateError(ViewDataDictionary ViewData, string str, int length, string error_field, string error_string)
        {
            int error_state = 0;
            if (str != null && str.Length > length)
            {
                error_state++;
                ViewData[error_field] = error_string + " is too long! Maximium " + length.ToString() + " characters!";
            }
            return error_state;
        }

        public object SearchClient(ref FormCollection form, ref int resultCount, string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchClientCriteria"].ToString();
            var searchString = form["searchString"];
            switch (searchCriteria) //value of radiobuttonList
            {
                case "_email":
                    return searchClientByEmail(ref form, ref resultCount, ref sortBy);
                    
                case "_name":
                    return searchClientByName(ref form, ref resultCount, ref sortBy);

                case "_passportNo":
                    return searchClientByPassport(ref form, ref resultCount, ref sortBy);
                    
                case "_country":
                    return searchClientByCountry(ref form, ref resultCount, ref sortBy);
                    
                default:
                    return RedirectToAction("Index");
            }
        }

        private object searchClientByCountry(ref FormCollection form, ref int resultCount, ref string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchClientCriteria"].ToString();
            var searchString = form["searchString"];
            var returnClientsCountry = from client in _hotelEntity.CLIENT
                                       where client.COUNTRY.ToLower().Contains(searchString.ToLower())
                                       select new
                                       {
                                           Email = client.EMAIL,
                                           Country = client.COUNTRY,
                                           FirstName = client.FIRSTNAME,
                                           LastName = client.LASTNAME,
                                           Gender = client.GENDER,
                                           Contact = client.CONTACT,
                                           Passport = client.PASSPORTNO
                                       };
            if (returnClientsCountry.ToList().Count() == 0)
            {
                return null;
            }
            else
            {
                resultCount = returnClientsCountry.ToList().Count;
                switch (sortBy)
                {
                    case "Email":
                    default:
                        return returnClientsCountry.OrderBy(client => client.Email.ToLower()).ToList();
                    case "FirstName":
                        return returnClientsCountry.OrderBy(client => client.FirstName).ToList();
                    case "LastName":
                        return returnClientsCountry.OrderBy(client => client.LastName).ToList();
                    case "Gender":
                        return returnClientsCountry.OrderBy(client => client.Gender).ToList();
                    case "Contact":
                        return returnClientsCountry.OrderBy(client => client.Contact).ToList();
                    case "Country":
                        return returnClientsCountry.OrderBy(client => client.Country).ToList();
                    case "Passport":
                        return returnClientsCountry.OrderBy(client => client.Passport).ToList();
                }
            }
        }

        private object searchClientByPassport(ref FormCollection form, ref int resultCount, ref string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchClientCriteria"].ToString();
            var searchString = form["searchString"];
            var returnClientsPassport = from client in _hotelEntity.CLIENT
                                        where client.PASSPORTNO.ToLower().Contains(searchString.ToLower())
                                        select new
                                        {
                                            Email = client.EMAIL,
                                            Passport = client.PASSPORTNO,
                                            FirstName = client.FIRSTNAME,
                                            LastName = client.LASTNAME,
                                            Gender = client.GENDER,
                                            Contact = client.CONTACT,
                                            Country = client.COUNTRY
                                        };
            if (returnClientsPassport.ToList().Count == 0)
            {
                return null;
            }
            else
            {
                resultCount = returnClientsPassport.ToList().Count;
                switch (sortBy)
                {
                    case "Email":
                    default:
                        return returnClientsPassport.OrderBy(client => client.Email.ToLower()).ToList();
                    case "FirstName":
                        return returnClientsPassport.OrderBy(client => client.FirstName).ToList();
                    case "LastName":
                        return returnClientsPassport.OrderBy(client => client.LastName).ToList();
                    case "Gender":
                        return returnClientsPassport.OrderBy(client => client.Gender).ToList();
                    case "Contact":
                        return returnClientsPassport.OrderBy(client => client.Contact).ToList();
                    case "Country":
                        return returnClientsPassport.OrderBy(client => client.Country).ToList();
                    case "Passport":
                        return returnClientsPassport.OrderBy(client => client.Passport).ToList();
                }
            }
        }

        private object searchClientByName(ref FormCollection form, ref int resultCount, ref string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchClientCriteria"].ToString();
            var searchString = form["searchString"];
            var returnClientsName = from client in _hotelEntity.CLIENT
                                    where client.FIRSTNAME.ToLower().Contains(searchString.ToLower()) || client.LASTNAME.ToLower().Contains(searchString.ToLower())
                                    select new
                                    {
                                        Email = client.EMAIL,
                                        FirstName = client.FIRSTNAME,
                                        LastName = client.LASTNAME,
                                        Gender = client.GENDER,
                                        Contact = client.CONTACT,
                                        Country = client.COUNTRY,
                                        Passport = client.PASSPORTNO
                                    };
            if (returnClientsName.ToList().Count == 0)
            {
                return null;
            }
            else
            {
                resultCount = returnClientsName.ToList().Count;
                switch (sortBy)
                {
                    case "Email":
                    default:
                        return returnClientsName.OrderBy(client => client.Email.ToLower()).ToList();
                    case "FirstName":
                        return returnClientsName.OrderBy(client => client.FirstName).ToList();
                    case "LastName":
                        return returnClientsName.OrderBy(client => client.LastName).ToList();
                    case "Gender":
                        return returnClientsName.OrderBy(client => client.Gender).ToList();
                    case "Contact":
                        return returnClientsName.OrderBy(client => client.Contact).ToList();
                    case "Country":
                        return returnClientsName.OrderBy(client => client.Country).ToList();
                    case "Passport":
                        return returnClientsName.OrderBy(client => client.Passport).ToList();
                }
            }
        }

        private object searchClientByEmail(ref FormCollection form, ref int resultCount, ref string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchClientCriteria"].ToString();
            var searchString = form["searchString"];
            var returnClientsEmail = from client in _hotelEntity.CLIENT
                                     where client.EMAIL.ToLower().Contains(searchString.ToLower())
                                     select new
                                     {
                                         Email = client.EMAIL,
                                         FirstName = client.FIRSTNAME,
                                         LastName = client.LASTNAME,
                                         Gender = client.GENDER,
                                         Contact = client.CONTACT,
                                         Country = client.COUNTRY,
                                         Passport = client.PASSPORTNO
                                     };
            if (returnClientsEmail.ToList().Count == 0)
            {
                return null;
            }
            else
            {
                resultCount = returnClientsEmail.ToList().Count;
                switch (sortBy)
                {
                    case "Email":
                    default:
                        return returnClientsEmail.OrderBy(client => client.Email.ToLower()).ToList();
                    case "FirstName":
                        return returnClientsEmail.OrderBy(client => client.FirstName).ToList();
                    case "LastName":
                        return returnClientsEmail.OrderBy(client => client.LastName).ToList();
                    case "Gender":
                        return returnClientsEmail.OrderBy(client => client.Gender).ToList();
                    case "Contact":
                        return returnClientsEmail.OrderBy(client => client.Contact).ToList();
                    case "Country":
                        return returnClientsEmail.OrderBy(client => client.Country).ToList();
                    case "Passport":
                        return returnClientsEmail.OrderBy(client => client.Passport).ToList();
                }
            }
        }

        public object SearchTransaction(ref FormCollection form, ref int resultCount, string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchBookingCriteria"].ToString();
            var searchString = form["searchString"];
            switch (searchCriteria) //value of radiobuttonList
            {
                case "_clientEmail":
                    return searchTransactionByClientEmail(ref form, ref resultCount, sortBy);

                case "_hotelName":
                    return searchTransactionByHotelName(ref form, ref resultCount, sortBy);


                default:
                    return RedirectToAction("Index");
            }
        }

        private object searchTransactionByHotelName(ref FormCollection form, ref int resultCount, string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchBookingCriteria"].ToString();
            var searchString = form["searchString"];
            var returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                         where (transaction.H_BRANCHNAME.ToLower().Contains(searchString)
                                         || transaction.H_NAME.ToLower().Contains(searchString)
                                         || transaction.H_COUNTRY.ToLower().Contains(searchString))
                                         select new
                                         {
                                             ID = transaction.BOOKINGID,
                                             Hotel_Name = transaction.H_BRANCHNAME,
                                             Country = transaction.H_COUNTRY,
                                             Email = transaction.C_EMAIL,
                                             Start = transaction.STARTDATE,
                                             End = transaction.ENDDATE
                                         };
            string startDate = form["startDate"].ToString();
            string endDate = form["endDate"].ToString();
            ViewData["startDate"] = form["StartDate"];
            ViewData["endDate"] = form["EndDate"];
            if (startDate != "")
            {
                DateTime start = DateTime.ParseExact(startDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);

                if (endDate != "")
                {
                    DateTime end = DateTime.ParseExact(endDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                             where (transaction.H_BRANCHNAME.ToLower().Contains(searchString)
                                         || transaction.H_NAME.ToLower().Contains(searchString)
                                         || transaction.H_COUNTRY.ToLower().Contains(searchString))
                                             && transaction.STARTDATE < end && transaction.STARTDATE > start
                                             select new
                                             {
                                                 ID = transaction.BOOKINGID,
                                                 Hotel_Name = transaction.H_BRANCHNAME,
                                                 Country = transaction.H_COUNTRY,
                                                 Email = transaction.C_EMAIL,
                                                 Start = transaction.STARTDATE,
                                                 End = transaction.ENDDATE
                                             };
                }
                else
                {
                    returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                             where (transaction.H_BRANCHNAME.ToLower().Contains(searchString)
                                         || transaction.H_NAME.ToLower().Contains(searchString)
                                         || transaction.H_COUNTRY.ToLower().Contains(searchString))
                                             && (transaction.STARTDATE > start)
                                             select new
                                             {
                                                 ID = transaction.BOOKINGID,
                                                 Hotel_Name = transaction.H_BRANCHNAME,
                                                 Country = transaction.H_COUNTRY,
                                                 Email = transaction.C_EMAIL,
                                                 Start = transaction.STARTDATE,
                                                 End = transaction.ENDDATE
                                             };
                }
            }
            else
            {
                if (endDate == "")
                {
                    returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                             where (transaction.H_BRANCHNAME.ToLower().Contains(searchString)
                                         || transaction.H_NAME.ToLower().Contains(searchString)
                                         || transaction.H_COUNTRY.ToLower().Contains(searchString))
                                             select new
                                             {
                                                 ID = transaction.BOOKINGID,
                                                 Hotel_Name = transaction.H_BRANCHNAME,
                                                 Country = transaction.H_COUNTRY,
                                                 Email = transaction.C_EMAIL,
                                                 Start = transaction.STARTDATE,
                                                 End = transaction.ENDDATE
                                             };
                }
                else
                {
                    DateTime end = DateTime.ParseExact(endDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                             where (transaction.H_BRANCHNAME.ToLower().Contains(searchString)
                                         || transaction.H_NAME.ToLower().Contains(searchString)
                                         || transaction.H_COUNTRY.ToLower().Contains(searchString))
                                             && transaction.STARTDATE < end
                                             select new
                                             {
                                                 ID = transaction.BOOKINGID,
                                                 Hotel_Name = transaction.H_BRANCHNAME,
                                                 Country = transaction.H_COUNTRY,
                                                 Email = transaction.C_EMAIL,
                                                 Start = transaction.STARTDATE,
                                                 End = transaction.ENDDATE
                                             };
                }
            }

            if (returnTransactionEmail.ToList().Count == 0)
            {
                return null;
            }
            else
            {
                resultCount = returnTransactionEmail.ToList().Count;
                switch (sortBy)
                {
                    case "ID":
                    default:
                        return returnTransactionEmail.OrderBy(client => client.ID).ToList();
                    case "Email":
                        return returnTransactionEmail.OrderBy(client => client.Email.ToLower()).ToList();
                    case "Hotel_Name":
                        return returnTransactionEmail.OrderBy(client => client.Hotel_Name).ToList();
                    case "Country":
                        return returnTransactionEmail.OrderBy(client => client.Country).ToList();
                    case "Start":
                        return returnTransactionEmail.OrderBy(client => client.Start).ToList();
                    case "End":
                        return returnTransactionEmail.OrderBy(client => client.End).ToList();
                }
            }
        }

        private object searchTransactionByClientEmail(ref FormCollection form, ref int resultCount, string sortBy)
        {
            var searchCriteria = form["ctl00$MainContent$dropdownlistSearchBookingCriteria"].ToString();
            var searchString = form["searchString"];
            var returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                         where transaction.C_EMAIL.ToLower().Contains(searchString)
                                         select new
                                         {
                                             ID = transaction.BOOKINGID,
                                             Email = transaction.C_EMAIL,
                                             Hotel_Name = transaction.H_BRANCHNAME,
                                             Country = transaction.H_COUNTRY,
                                             Start = transaction.STARTDATE,
                                             End = transaction.ENDDATE
                                         };
            string startDate = form["startDate"].ToString();
            string endDate = form["endDate"].ToString();
            ViewData["startDate"] = form["StartDate"];
            ViewData["endDate"] = form["EndDate"];
           if (startDate != "")
            {
                DateTime start = DateTime.ParseExact(startDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
            
                if (endDate != "")
                {
                    DateTime end = DateTime.ParseExact(endDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                             where transaction.C_EMAIL.ToLower().Contains(searchString)
                                             && transaction.STARTDATE < end && transaction.STARTDATE > start
                                             select new
                                             {
                                                 ID = transaction.BOOKINGID,
                                                 Email = transaction.C_EMAIL,
                                                 Hotel_Name = transaction.H_BRANCHNAME,
                                                 Country = transaction.H_COUNTRY,
                                                 Start = transaction.STARTDATE,
                                                 End = transaction.ENDDATE
                                             };
                }
                else
                {
                    returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                             where transaction.C_EMAIL.ToLower().Contains(searchString)
                                             && (transaction.STARTDATE > start)
                                             select new
                                             {
                                                 ID = transaction.BOOKINGID,
                                                 Email = transaction.C_EMAIL,
                                                 Hotel_Name = transaction.H_BRANCHNAME,
                                                 Country = transaction.H_COUNTRY,
                                                 Start = transaction.STARTDATE,
                                                 End = transaction.ENDDATE
                                             };
                }
            }
            else
            {
                if (endDate == "")
                {
                    returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                             where transaction.C_EMAIL.ToLower().Contains(searchString)
                                             select new
                                             {
                                                 ID = transaction.BOOKINGID,
                                                 Email = transaction.C_EMAIL,
                                                 Hotel_Name = transaction.H_BRANCHNAME,
                                                 Country = transaction.H_COUNTRY,
                                                 Start = transaction.STARTDATE,
                                                 End = transaction.ENDDATE
                                             };
                }
                else
                {
                    DateTime end = DateTime.ParseExact(endDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    returnTransactionEmail = from transaction in _hotelEntity.BOOKING
                                             where transaction.STARTDATE < end
                                             select new
                                             {
                                                 ID = transaction.BOOKINGID,
                                                 Email = transaction.C_EMAIL,
                                                 Hotel_Name = transaction.H_BRANCHNAME,
                                                 Country = transaction.H_COUNTRY,
                                                 Start = transaction.STARTDATE,
                                                 End = transaction.ENDDATE
                                             };
                }
            }
            
            if (returnTransactionEmail.ToList().Count == 0)
            {
                return null;
            }
            else
            {
                resultCount = returnTransactionEmail.ToList().Count;
                switch (sortBy)
                {
                    case "ID":
                    default:
                        return returnTransactionEmail.OrderBy(client => client.ID).ToList();
                    case "Email":
                        return returnTransactionEmail.OrderBy(client => client.Email.ToLower()).ToList();
                    case "Hotel_Name":
                        return returnTransactionEmail.OrderBy(client => client.Hotel_Name).ToList();
                    case "Country":
                        return returnTransactionEmail.OrderBy(client => client.Country).ToList();
                    case "Start":
                        return returnTransactionEmail.OrderBy(client => client.Start).ToList();
                    case "End":
                        return returnTransactionEmail.OrderBy(client => client.End).ToList();
                }
            }
        }





       /***************************************************View Client Start****************************************************/

        public object ViewDetailsClient(string userEmail)
        {

            var resultClient = viewClient(userEmail);
            if (resultClient == null)
            {
                ViewData["clientModel"] = "";
            }
            else
            {
                ViewData["clientModel"] = resultClient;
            }
            ViewData["userEmail"] = userEmail;
            return View();
        }

        private object viewClient(string userEmail)
        {
            try
            {
                var clientReturn = (from client in _hotelEntity.CLIENT
                                       where client.EMAIL.Equals(userEmail)
                                       select client);
                return clientReturn.First();
            }
            catch
            {
                return null;
            }
        }







       /***************************************************View Client End****************************************************/
        private SelectList getBranchNames(string hotel_name, string country_name, string selected = null)
        {
            var branch_names = new SelectList((from Hotel in _hotelEntity.HOTEL
                                               where Hotel.HOTEL_NAME == hotel_name &&
                                               Hotel.COUNTRY == country_name
                                               select new SelectListItem
                                               {
                                                   Text = Hotel.BRANCHNAME,
                                                   Value = Hotel.BRANCHNAME
                                               }).Distinct(), "Value", "Text", selected);
            return branch_names;
        }
        private void populateHotelListForDropDownList(ViewDataDictionary ViewData, string hotel_name, string country_name, string branch_name)
        {
            var hotel_names = getHotelNames(hotel_name);
            var country_names = getCountryNames(hotel_name, country_name);
            var branch_names = getBranchNames(hotel_name, country_name, branch_name);
            ViewData["hotel_names"] = hotel_names;
            ViewData["country_names"] = country_names;
            ViewData["branch_names"] = branch_names;
        }
        private SelectList getHotelNames(string selected = null)
        {
            var hotel_names = new SelectList((from Hotel in _hotelEntity.HOTEL
                                              select new SelectListItem
                                              {
                                                  Text = Hotel.HOTEL_NAME,
                                                  Value = Hotel.HOTEL_NAME
                                              }).Distinct(), "Value", "Text", selected);
            return hotel_names;
        }
        private SelectList getCountryNames(string hotel_name, string selected = null)
        {
            var country_names = new SelectList((from Hotel in _hotelEntity.HOTEL
                                                where (Hotel.HOTEL_NAME == hotel_name)
                                                select new SelectListItem
                                                {
                                                    Text = Hotel.COUNTRY,
                                                    Value = Hotel.COUNTRY
                                                }).Distinct(), "Value", "Text", selected);
            return country_names;
        }
        private void ValidateEmail(string email)
        {

            if (String.IsNullOrEmpty(email))
            {
                ModelState.AddModelError("EMAIL", "* Email is required!");
            }
            else if (!System.Text.RegularExpressions.Regex.IsMatch(email, "^(?('')(''.+?''@)|(([0-9a-zA-Z]((\\.(?!\\.))|[-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*)(?<=[0-9a-zA-Z])@))(?(\\[)(\\[(\\d{1,3}\\.){3}\\d{1,3}\\])|(([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,6}))$"))
            {
                ModelState.AddModelError("EMAIL", "* Value entered must be an Email");
            }

        }

        private void ValidatePWD(string password)
        {
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("PWD", "* Password is required!");
            }
            else if (System.Text.RegularExpressions.Regex.IsMatch(password, "(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$"))
            {

            }

        }
        private void ValidateAddress(string address)
        {
            if (String.IsNullOrEmpty(address))
            {
                ModelState.AddModelError("ADDRESS", "* Email is required!");
            }
        }
        private void ValidateCountry(string country)
        {
            if (String.IsNullOrEmpty(country))
            {
                ModelState.AddModelError("COUNTRY", "* Country is required!");
            }
        }
        private void ValidateName(string designation, string firstName, string lastName)
        {
            if (String.IsNullOrEmpty(designation))
            {
                ModelState.AddModelError("DESIGNATION", "* Designation is required!");
            }
            if (firstName == "First Name")
            {
                ModelState.AddModelError("FIRSTNAME", "* First Name is required!");
            }
            if (lastName == "Last Name")
            {
                ModelState.AddModelError("LASTNAME", "* Last Name is required!");
            }
        }
        private void ValidatePassport(string passport)
        {
            if (String.IsNullOrEmpty(passport))
            {
                ModelState.AddModelError("PASSPORTNO", "* Passport No. is required!");
            }
        }
        private void ValidateGender(string gender)
        {
            if (String.IsNullOrEmpty(gender))
            {
                ModelState.AddModelError("GENDER", "* Select one of the option");
            }
        }
        private void ValidateContact(string contact)
        {
            if (String.IsNullOrEmpty(contact))
            {
                ModelState.AddModelError("CONTACT", "* Contact is required!");
            }
            else if (!System.Text.RegularExpressions.Regex.IsMatch(contact, "\\d*"))
            {
                ModelState.AddModelError("CONTACT", "* Contact only numeric");
            }
        }
        private Boolean ChkValidUser()
        {

            UserModel user = (UserModel)Session["User"];
            if (string.IsNullOrEmpty(user.Email))
                return false;
            return true;
        }
    }
}
